#!/usr/bin/python3.2
#voir pour envoie à plusieurs personnes

import re
import Mail
import builtins

def searchDbContact(nom):
    dbFile=open("database/contacts","r")
    tab=[]
    for ligne in dbFile:
        temp=ligne.strip().split(";")
        name=temp[0].split(",")
        for n in name:
            if re.search(nom,n,re.IGNORECASE):
                tab.append(temp[0])
    return tab

def saveDbContact(nom,email):
    dbFile=open("database/contacts","a")
    dbFile.write(nom+";"+email+"\n")

def contactFromDb(nom):
    dbFile=open("database/contacts","r")
    email="non trouvé"
    for ligne in dbFile:
        temp=ligne.strip().split(";")
        if nom.lower() == temp[0].lower() :
            email=temp[1]
    return email

def contactFromGmail():
    return ""

def contactFromHotmail():
    return ""

def contactFromOS():
    return ""

def complete(email,subject,content):
    res="ok"
    if email!="" and subject!="" and content!="":
#        res=Mail.sendTextMail(subject,content,email)
        for dest in email:
            res=Mail.sendHtmlMail(subject,content,dest)
    return res


def sendMail(nom,subject="",content=""):
    error=""
    quest=""
    fct="Contact.sendMail"
    n=nom.split(" ")
    email=[]
    for name in n:
        tab=searchDbContact(name)
        if len(tab) == 1:
            email.append(contactFromDb(tab[0]))
        elif len(tab) > 1 :
            print("plusieurs noms correspondent")
            for i in range(len(tab)):
                print(str(i)+" "+tab[i]+" (bdd)")
            num=input("Entrer le numéro du contact choisit: ")
            email.append(contactFromDb(tab[int(num)]))
        else:
            print("Destinataire inconnu")
            email.append(input("Entrer l'adresse mail du contact"))
            saveDbContact(nom,email)
    if subject=="":
        error="manqueSujet"
        quest="Quel est le sujet du mail?"
    elif content=="":
        error="manqueContent"
        quest="Que dois-je mettre comme contenu?"
    else:
        error=complete(email,subject,content)
        quest="mail envoyé"
    return error,quest,fct
